<?php

	require_once(dirname(dirname(dirname(dirname(__FILE__)))) . "/engine/start.php");
	gatekeeper(); 
	
	$session = get_entity(get_input("chatsession"));
	$offset = get_input("offset");
		
	if($session){
		
		$current_user = get_loggedin_user();

		$maxmembers = get_entities_from_relationship("elggchat_session_member", $session->guid, null, null, null, null, null, null, null, true);
		$members = get_entities_from_relationship("elggchat_session_member", $session->guid, null, null, null, null, null, $maxmembers);
		
		if(check_entity_relationship($session->guid, "elggchat_session_member_invite", $current_user->guid)){
			
			
			$sessioninformation = elgg_echo('elggchat:session_info:members') . "<br>";
			foreach($members as $member){
				$sessioninformation .= "- " . $member->name . "</br>";
			}
			
			remove_entity_relationship( $session->guid,"elggchat_session_member_invite", $current_user->guid); 
			add_entity_relationship( $session->guid,"elggchat_session_member", $current_user->guid); 
			
			$message = sprintf(elgg_echo('elggchat:action:join'),$current_user->name);
			$session->annotate("elggchat_system_message", $message,ACCESS_LOGGED_IN,$current_user->guid);
			$session->annotate("elggchat_system_message", $sessioninformation,ACCESS_PRIVATE,$current_user->guid);
			
			
		}		
		// check if caller is session member
		
		if(is_member($current_user->guid, $members)){

			if(empty($offset) || $offset == 'undefined'){
				$offset = 0;
			}
			
			$join_annotation = get_annotations($session->guid,"","","elggchat_system_message", sprintf(elgg_echo('elggchat:action:join'),$current_user->name),0,1,0,"desc");
			$joined_timestamp = $join_annotation[0]->time_created;
		
			$messages = $session->getAnnotations("",9999,$offset);
			$recNum = 0;
			foreach($messages as $message){
				
				$recNum++;
				if($message->time_created >= $joined_timestamp){
					$user = get_entity($message->owner_guid);
					echo elgg_view("elggchat/message", array("message"=>$message, "message_owner"=>$user, "offset"=>$offset + $recNum));
				}
			}
		}
		// update session last active (cron will delete it if not active for a while)
		$session->save();
		
	}
	exit();
?>
